# -*- coding: utf-8 -*-
"""
Chapter 1: Basic Flask Application with Routing

This demo covers:
- Creating a basic Flask application
- Defining routes with @app.route decorator
- Using URL variables and converters
- Creating custom CLI commands
"""

import os

import click
from flask import Flask

# Create Flask application instance
app = Flask(__name__)


# Basic route returning HTML
@app.route('/')
def index():
    """Root route returning a simple greeting."""
    return '<h1>Welcome to Flask!</h1><p>This is the home page.</p>'


# Multiple routes for the same view function
@app.route('/hi')
@app.route('/hello')
def say_hello():
    """Multiple routes pointing to the same function."""
    return '<h1>Hello, Flask Developer!</h1>'


# Route with URL variable
@app.route('/user/<name>')
def user(name):
    """Route with a string variable."""
    return f'<h1>Hello, {name}!</h1>'


# Route with integer converter
@app.route('/post/<int:post_id>')
def show_post(post_id):
    """Route with an integer variable."""
    return f'<h1>Post ID: {post_id}</h1><p>You are viewing post #{post_id}.</p>'


# Route with float converter
@app.route('/weight/<float:weight>')
def show_weight(weight):
    """Route with a float variable."""
    return f'<h1>Weight: {weight:.2f}kg</h1>'


# Route with path converter (accepts slashes)
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    """Route with a path variable that accepts slashes."""
    return f'<h1>Subpath: {subpath}</h1>'


# Route with default value
@app.route('/greet', defaults={'name': 'Guest'})
@app.route('/greet/<name>')
def greet(name):
    """Route with a default value for the name parameter."""
    return f'<h1>Hello, {name}!</h1>'


# Custom Flask CLI command
@app.cli.command()
def init_db():
    """Initialize the database."""
    click.echo('Initializing the database...')
    # In a real application, you would initialize your database here
    click.echo('Database initialized!')


# Another custom CLI command with parameters
@app.cli.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(name):
    """Simple CLI command to say hello."""
    click.echo(f'Hello, {name}! Welcome to Flask development.')
    """
    >flask --app app.py hello
    Your name: jack
    Hello, jack! Welcome to Flask development.
    
    >flask hello             
    Your name: kitty
    Hello, kitty! Welcome to Flask development.
    """


if __name__ == '__main__':
    # Run the application
    # Note: In production, use a proper WSGI server like Gunicorn
    app.run(
        host=os.getenv('FLASK_HOST', '127.0.0.1'),
        port=int(os.getenv('FLASK_PORT', 5000)),
        debug=os.getenv('FLASK_DEBUG', 'True').lower() == 'true'
    )
